package com.demo.ipcSocket;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author MT
 * 模拟客户端
 * @date 2019-12-09 13:26
 */
@Slf4j
public class ChatClient {
    public static void main(String[] args) throws IOException {

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 5; i++) {
//            TimeUnit.SECONDS.sleep(5);
            executorService.submit(() -> {

                // 要连接的服务端IP地址和端口
                String host = "192.168.1.163";
                int port = 8081;
                // 与服务端建立连接
                Socket socket = null;
                try {
                    socket = new Socket(host, port);
                    // 建立连接后获得输出流
                    OutputStream outputStream = socket.getOutputStream();
                    String message = UUID.randomUUID().toString();
                    byte[] messageBytes = message.getBytes("UTF-8");
                    socket.setSendBufferSize(messageBytes.length);
                    socket.getOutputStream().write(messageBytes);
                    // 必需关闭输出流
                    socket.shutdownOutput();
                    // 获取输出流
                    InputStream inputStream = socket.getInputStream();
                    byte[] bytes = new byte[1024];
                    int len;
                    StringBuilder sb = new StringBuilder();
                    while ((len = inputStream.read(bytes)) != -1) {
                        //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                        sb.append(new String(bytes, 0, len, "UTF-8"));
                    }
                    log.info("get message from server: " + sb);

                    inputStream.close();
                    outputStream.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();
    }
}
